/*
 *  Openmysee
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
				 
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define _GNU_SOURCE
#include <getopt.h>

#define MAX_DATA	16384
struct BlockData
{
	int id;
	int size;
	char block[MAX_DATA];
};
int
main (int argc, char **argv)
{
	int change = 0, size = 16384;;
	int i=0, j=0, c, num=1256, k=0;
	FILE *in=NULL, *out=NULL;
	struct BlockData b;
	char block[MAX_DATA];
	char buffer[MAX_DATA];
	char *p = block;

	while ((c=getopt (argc, argv, "cnv")) != -1)
	{
		switch (c)
		{
			case 'c':
				change = 1;
				break;
			case 'n':
				num = atoi (optarg);
				break;
			case 'v':
			default:
				fprintf (stderr, "%s file_to_be_changed\n", argv[0]);
				exit (EXIT_FAILURE);
		}
	}
	if (change == 1)
	{
		size = sizeof (b);
		p = (char *)(&b);
	}
	mkdir ("CHANGED", 0777);
	
	while (1)
	{
		snprintf (buffer, sizeof(buffer), "%d", j);
		if ((in = fopen (buffer, "r")) == NULL)
		{
			fprintf (stderr, "%s cannot be opened.\n", argv[i]);
			goto OUT;
		}
		while (fread (p, size, 1, in) == 1)
		{
			if (k >= num || out == NULL)
			{
				if (out != NULL) fclose (out);
				snprintf (buffer, MAX_DATA, "CHANGED/%d", i);
				if ((out = fopen (buffer, "w")) == NULL)
				{
					fprintf (stderr, "%s cannot be opened.\n", buffer);
					perror ("fopen");
					fclose (in);
					goto OUT;
				}
				i++;
				k=0;
			}
			if (change)
				fwrite (b.block, b.size, 1, out);
			else
				fwrite (block, size, 1, out);
			k ++;
		}
		fclose (in);
		j++;
	}
OUT:
	printf ("Total %d changed, saved to %d files.\n", j, i);
	return 0;
}
